package com.zlsx.flowview;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import java.lang.reflect.Field;

import static android.content.ContentValues.TAG;


public class FloatViewService extends Service {
    // 定义浮动窗口布局
    private LinearLayout mFloatLayout;
    private LayoutParams wmParams;
    // 创建浮动窗口设置布局参数的对象
    private WindowManager mWindowManager;
    private Handler handlerLeft = new Handler(), handlerRight = new Handler();
    private Runnable Left, right;
    private ImageButton mFloatView;
    private int screenHeight;
    private int screenWidth;
    private MyCountDownTimer myCountDownTimer;
    private boolean reset;
    private boolean isClick;
    private float rawX;
    private float rawY;
    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > 24) {
            try {
                Class clazz = Settings.class;
                Field field = clazz.getDeclaredField(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                Intent intent = new Intent(field.get(null).toString());
                Log.i("FLAG_ACTIVITY_NEW_TASK", "Karl-Dujinyang");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("package:" + getApplication().getPackageName()));
                getApplication().startActivity(intent);
            } catch (Exception e) {
                Log.e("Exception", "permission " + e.getMessage());
            }
        }

        //获取屏幕宽度高度
        Log.i(TAG, "onCreate: zlsx 服务启动");
        Point point = new Point();
        WindowManager manager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getSize(point);
        screenWidth = point.x;
        screenHeight = point.y;
        createFloatView();
        myCountDownTimer = new MyCountDownTimer(2500, 500);
        myCountDownTimer.start();
    }

    @SuppressWarnings("static-access")
    @SuppressLint({"InflateParams", "ClickableViewAccessibility"})
    private void createFloatView() {
        wmParams = new LayoutParams();
        // 通过getApplication获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        if (Build.VERSION.SDK_INT > 24) {
            wmParams.type = LayoutParams.TYPE_PHONE;
        } else {
            wmParams.type = LayoutParams.TYPE_TOAST;
        }
        // 设置window type
        /* wmParams.type = LayoutParams.TYPE_TOAST;*/
        // 设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        // 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
        // 调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.RIGHT | Gravity.BOTTOM;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = 0;
        wmParams.y = screenHeight / 2;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mFloatLayout.scrollTo(-(mFloatView.getWidth() / 2), 0);
                reset = true;
            }
        }, 2000);
        // 设置悬浮窗口长宽数据
        wmParams.width = LayoutParams.WRAP_CONTENT;
        wmParams.height = LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        // 获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.alert_window_menu, null);
        // 添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);
        // 浮动窗口按钮
        mFloatView = (ImageButton) mFloatLayout.findViewById(R.id.alert_window_imagebtn);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        // 设置监听浮动窗口的触摸移动
        mFloatView.setOnTouchListener(new OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isClick = false;
                        if (Left != null)
                            handlerLeft.removeCallbacks(Left);
                        if (right != null)
                            handlerRight.removeCallbacks(right);
                        if (reset) {
                            mFloatLayout.scrollTo(0, 0);
                        }
                        mFloatLayout.setAlpha(1.0f);
                        myCountDownTimer.cancel();
                        mFloatLayout.scrollTo(0, 0);
                        rawX = event.getRawX();
                        rawY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        isClick = true;
                        if (Left != null)
                            handlerLeft.removeCallbacks(Left);
                        if (right != null)
                            handlerRight.removeCallbacks(right);
                        if (reset) {
                            mFloatLayout.scrollTo(0, 0);
                        }
                        int distanceX = (int) (event.getRawX() - rawX);
                        int distanceY = (int) (event.getRawY() - rawY);
                        wmParams.x = wmParams.x - distanceX;
                        wmParams.y = wmParams.y - distanceY;
                        // 刷新
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                        rawX = event.getRawX();
                        rawY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        myCountDownTimer.start();
                        Left = new Runnable() {
                            @Override
                            public void run() {
                                mFloatLayout.scrollTo(-(mFloatView.getWidth() / 2), 0);
                                reset = true;
                            }
                        };
                        right = new Runnable() {
                            @Override
                            public void run() {
                                mFloatLayout.scrollTo(mFloatView.getWidth() / 2, 0);
                                reset = true;
                            }
                        };
                        if (wmParams.x <= mFloatView.getWidth()) {
                            wmParams.x = 0;
                            handlerLeft.postDelayed(Left, 2000);
                        } else if (wmParams.x >= (screenWidth - mFloatView.getWidth())) {
                            wmParams.x = screenWidth;
                            handlerRight.postDelayed(right, 2000);
                        }
                        mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                        break;
                }
                return isClick;
            }
        });
        /**
         * Toast ：返回功能这样写的话需要系统签名才能运行
         * 如果想避开系统签名则需用户手动开启辅助服务选项
         */
        mFloatView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            Log.e("Exception when onBack", e.toString());
                        }
                    }
                }.start();
                /**
                 * 辅助功能写法
                 */
/*
                if(PermissionUtil.isAccessibilitySettingsOn(FloatViewService.this)){
                    AccessibilityUtil.onBack();
                }else{
                    Intent intent=new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }*/

            }
        });
    }

    /**
     * 防止服务被其他应用杀死，destroy后重新启动服务
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }
        Intent service = new Intent(getApplication(), FloatViewService.class);
        getApplication().startService(service);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //延时透明
    public class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            mFloatLayout.setAlpha(0.4f);
        }
    }

}
